package p.ithorns.framework.xxljob;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import p.ithorns.framework.common.utils.StringUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * xxljob服务配置类
 *
 * @author WeiZiDong
 * @since 2023-09-08 10:57:55
 **/
@Configuration
@EnableConfigurationProperties(XxlJobConf.class)
//@ConditionalOnProperty(prefix = "service", value = "is-cluster", havingValue = "true")
public class XxlJobAutoConfiguration {

    private final static Logger log = LoggerFactory.getLogger(XxlJobAutoConfiguration.class);

    @DependsOn({"appContext"})
    @Bean("xxlJobOperator")
    public XxlJobSpringExecutor xxlJobExecutor(AppContext context, XxlJobConf conf) throws UnknownHostException {
        // XxlJobAdminBizClient adminBizClient = new XxlJobAdminBizClient(context, conf);
        // XxlJobSpringExecutor xxlJobSpringExecutor = new ExtXxlJobSpringExecutor(adminBizClient);

        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        XxlJobConf.Admin admin = conf.getAdmin();
        XxlJobConf.Executor executor = conf.getExecutor();
        xxlJobSpringExecutor.setAdminAddresses(admin.getAddresses());
        xxlJobSpringExecutor.setAppname(executor.getAppName());
        xxlJobSpringExecutor.setAccessToken(conf.getAccessToken());

        String executorIp = StringUtil.isNotBlank(executor.getIp())
                ? executor.getIp()
                :  InetAddress.getLocalHost().getHostAddress();
        int port = executor.getPort();
        xxlJobSpringExecutor.setIp(executorIp);
        xxlJobSpringExecutor.setPort(port);

        log.info(">>>> xxl-job-executor config init -> [{}:{}]", executorIp, port);
        return xxlJobSpringExecutor;
    }

    @DependsOn({"appContext"})
    @Bean
    public XxlJobOperator xxlJobManager(AppContext context, XxlJobConf conf) {
        return new XxlJobOperator(conf);
    }


    @Bean
    public XxlJobAutoRegister xxlJobAutoRegister(ApplicationContext appCtx,
                                                 Environment environment,
                                                 XxlJobOperator jobOperator) {
        return new XxlJobAutoRegister(appCtx, environment, jobOperator);
    }

}